<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Index extends CI_Controller {

    protected $data;
    public function __construct()
    {
        // Call the CI_Model constructor
        parent::__construct();
        $this->load->model('event');
        $this->load->library('pagination');
        $this->data['base_url'] = $this->config->config['base_url'];
        session_start();
        if(!isset($_SESSION['user_id']) || !isset($_SESSION['username'])){
            echo '<script>alert("未登录！");window.location.href="'.$this->data['base_url'].'/index.php/admin/login";</script>';
            exit;
        }
    }


	public function index()
	{
        $page = isset($_GET['per_page']) && is_numeric($_GET['per_page']) ? $_GET['per_page'] : 0;
        $event = isset($_GET['event']) && is_numeric($_GET['event']) ? $_GET['event'] : 1;
        $pagesize = 20;
        $where = array('event'=>$event);
        $count = $this->event->get_all_by_event($where);
        //分页
        $config['base_url'] = $this->data['base_url'].'/index.php/admin/index';
        $config['total_rows'] = $count;
        $config['per_page'] = 20;
        $config['page_query_string'] = TRUE;
        $config['cur_tag_open'] = '<li><a>';
        $config['cur_tag_close'] = '</li></a>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['next_link'] = '下一页';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['prev_link'] = '上一页';
        $this->pagination->initialize($config);
        $this->data['page'] = $this->pagination->create_links();
        $this->pagination->initialize($config);
        $this->data['data'] = $this->event->get_events_by($where,$pagesize, $page);
        $this->data['curr'] = 'index'.$event;
		$this->load->view('admin/index', $this->data);
	}

    public function sendevent()
    {
        $id = isset($_GET['id']) && is_numeric($_GET['id']) ? $_GET['id'] : null;
        if($id === null){
            echo '<script>alert("操作失败");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/index";</script>';exit;
        }
        $this->event->update_event($id);
        echo '<script>alert("操作成功");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/index";</script>';exit;
    }

    public function countprize()
    {
        $page = isset($_GET['per_page']) && is_numeric($_GET['per_page']) ? $_GET['per_page'] : 0;
        $pagesize = 20;
        $count = $this->prize->get_prize_count_all();
        //分页
        $config['base_url'] = $this->data['base_url'].'/index.php/admin/index/countprize';
        $config['total_rows'] = $count;
        $config['per_page'] = 20;
        $config['page_query_string'] = TRUE;
        $config['cur_tag_open'] = '<li><a>';
        $config['cur_tag_close'] = '</li></a>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['next_link'] = '下一页';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['prev_link'] = '上一页';
        $this->pagination->initialize($config);
        $this->data['page'] = $this->pagination->create_links();
        $this->pagination->initialize($config);
        $this->data['data'] = $this->prize->get_prize_count($pagesize, $page);
        $this->data['curr'] = 'countprize';
        $this->load->view('admin/countprize', $this->data);
    }


    public function password(){
        $this->data['curr'] = 'password';
        $this->load->view('admin/password', $this->data);
    }

    public function editpassword()
    {
        $old_pwd = isset($_POST['old_pwd']) && strlen($_POST['old_pwd']) ? trim($_POST['old_pwd']) : null;
        $new_pwd = isset($_POST['new_pwd']) && strlen($_POST['new_pwd']) ? trim($_POST['new_pwd']) : null;
        $re_pwd = isset($_POST['re_pwd']) && strlen($_POST['re_pwd']) ? trim($_POST['re_pwd']) : null;
        if($old_pwd === null || $new_pwd === null && $re_pwd === null){
            echo '<script>alert("填写不能为空");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/password";</script>';exit;
        }
        if($re_pwd != $new_pwd){
            echo '<script>alert("新密码和确认密码不一样");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/password";</script>';exit;
        }
        $user = $this->user->get_user(array('username' => 'admin'));
        if($user){
            if($user['password'] != md5($old_pwd)){
                echo '<script>alert("老密码错误");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/password";</script>';exit;
            }else{
                $this->user->update_user(array('password' => md5($new_pwd)));
                echo '<script>alert("修改成功！");window.location.href="'.$this->data['base_url'].'/index.php/admin/index/password";</script>';exit;
            }
        }
    }

    public function excel()
    {
        $this->data['data']  = $this->user->get_prize_use_data();
        $this->data['curr'] = 'excel';
        $this->load->view('admin/excel', $this->data);
    }


    public function getcsv()
    {
        $time = isset($_GET['time']) ? $_GET['time'] : 0;

        ini_set("max_execution_time", "3600");
        $csv_data = '';
        $title_arr = array('手机号','时间','奖品金额');
        /** 标题 */
        $nums = count($title_arr);
        for ($i = 0; $i < $nums - 1; ++$i) {
            $csv_data .= '"' . $title_arr[$i] . '",';
        }
        if ($nums > 0) {
            $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
        }

        $data  = $this->user->get_prize_use_data_detail($time);
        foreach ($data as $k => $row) {
            $row = array_values($row);
            for ($i = 0; $i < $nums - 1; ++$i) {
                $row[$i] = str_replace("\"", "\"\"", $row[$i]);
                $csv_data .= '"' . $row[$i] . '",';
            }
            $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
            unset($data[$k]);
        }
        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
        $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { // 解决IE浏览器输出中文名乱码的bug
            $file_name = urlencode($file_name);
            $file_name = str_replace('+', '%20', $file_name);
        }
        $file_name = $file_name . '.csv';
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

    /**
     * 参团名单
     */
    public function tuan()
    {
        $page = isset($_GET['per_page']) && is_numeric($_GET['per_page']) ? $_GET['per_page'] : 0;
        $count = $this->tuan->get_tuan(array('status' => 1),'count(*) as count');
        //分页
        $config['base_url'] = $this->data['base_url'].'/index.php/admin/index/tuan';
        $config['total_rows'] = !empty($count) ? $count[0]['count'] : 0;
        $config['per_page'] = 20;
        $config['page_query_string'] = TRUE;
        $config['cur_tag_open'] = '<li><a>';
        $config['cur_tag_close'] = '</li></a>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['next_link'] = '下一页';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['prev_link'] = '上一页';
        $this->pagination->initialize($config);
        $this->data['page'] = $this->pagination->create_links();
        $this->pagination->initialize($config);
        $tuan = $this->tuan->get_tuan(array('status' => 1), 'tuan.*,weixin_mobile.mobile',$page, $config['per_page']);
        if($tuan){
            foreach($tuan as $key =>$val){
                $r = $this->tuan->get_tuan_member(array('tuanyuan.tuan_id' => $val['id'], 'weixin_mobile.mobile != ' => $val['mobile']),'weixin_mobile.mobile');
                $tuanyuan = '';
                if($r){
                    foreach($r as $v){
                        $tuanyuan .= $v['mobile'].',';
                    }
                    $tuanyuan = substr($tuanyuan,0,-1);
                }else{
                    $tuanyuan = '';
                }
                $tuan[$key]['tuanyuan'] = $tuanyuan;
            }
        }

        $this->data['data'] = $tuan;
        $this->data['curr'] = 'tuan';
        $this->load->view('admin/tuan', $this->data);
    }


    public function downcsv()
    {
        $time = isset($_GET['time']) ? $_GET['time'] : 0;

        ini_set("max_execution_time", "3600");
        $csv_data = '';
        $title_arr = array('团长','团员','建团时间');
        /** 标题 */
        $nums = count($title_arr);
        for ($i = 0; $i < $nums - 1; ++$i) {
            $csv_data .= '"' . $title_arr[$i] . '",';
        }
        if ($nums > 0) {
            $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
        }

        $tuan = $this->tuan->get_tuan(array('status' => 1), 'tuan.*,weixin_mobile.mobile');
        if($tuan){
            foreach($tuan as $key =>$val){
                $r = $this->tuan->get_tuan_member(array('tuanyuan.tuan_id' => $val['id'], 'weixin_mobile.mobile != ' => $val['mobile']),'weixin_mobile.mobile');
                $tuanyuan = '';
                if($r){
                    foreach($r as $v){
                        $tuanyuan .= $v['mobile'].',';
                    }
                    $tuanyuan = substr($tuanyuan,0,-1);
                }else{
                    $tuanyuan = '';
                }
                $tuan[$key]['tuanyuan'] = $tuanyuan;
            }
        }
        $data = $tuan;
        foreach ($data as $k => $row) {
            $row = array_values($row);
            for ($i = 0; $i < $nums - 1; ++$i) {
                $row[$i] = str_replace("\"", "\"\"", $row[$i]);
                switch($i){
                    case 0 : $csv_data .= '"' . $row[4] . ',",';break;
                    case 1 : $csv_data .= '"' . $row[5] . ',",';break;
                    case 2 : $csv_data .= '"' . $row[2] . '",';break;
                }
            }
            $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
            unset($data[$k]);
        }
        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
        $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { // 解决IE浏览器输出中文名乱码的bug
            $file_name = urlencode($file_name);
            $file_name = str_replace('+', '%20', $file_name);
        }
        $file_name = $file_name . '.csv';
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

    /**
     * 参团名单
     */
    public function cartuan()
    {
        $page = isset($_GET['per_page']) && is_numeric($_GET['per_page']) ? $_GET['per_page'] : 0;
        $count = $this->cartuan->get_cartuan(array('status' => 1),'count(*) as count');
        //分页
        $config['base_url'] = $this->data['base_url'].'/index.php/admin/index/cartuan';
        $config['total_rows'] = !empty($count) ? $count[0]['count'] : 0;
        $config['per_page'] = 20;
        $config['page_query_string'] = TRUE;
        $config['cur_tag_open'] = '<li><a>';
        $config['cur_tag_close'] = '</li></a>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['next_link'] = '下一页';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['prev_link'] = '上一页';
        $this->pagination->initialize($config);
        $this->data['page'] = $this->pagination->create_links();
        $this->pagination->initialize($config);
        $tuan = $this->cartuan->get_cartuan(array('status' => 1), 'cartuan.*, car_weixin_mobile.mobile ',$page, $config['per_page']);
        if($tuan){
            foreach($tuan as $key =>$val){
                $r = $this->cartuan->get_cartuan_member(array('cartuanyuan.tuan_id' => $val['id'], 'car_weixin_mobile.mobile != ' => $val['mobile']),'car_weixin_mobile.mobile');
                $tuanyuan = '';
                if($r){
                    foreach($r as $v){
                        $tuanyuan .= $v['mobile'].',';
                    }
                    $tuanyuan = substr($tuanyuan,0,-1);
                }else{
                    $tuanyuan = '';
                }
                $tuan[$key]['tuanyuan'] = $tuanyuan;
            }
        }

        $this->data['data'] = $tuan;
        $this->data['curr'] = 'cartuan';
        $this->load->view('admin/cartuan', $this->data);
    }


    public function cardowncsv()
    {
        $time = isset($_GET['time']) ? $_GET['time'] : 0;

        ini_set("max_execution_time", "3600");
        $csv_data = '';
        $title_arr = array('团长','团员','建团时间');
        /** 标题 */
        $nums = count($title_arr);
        for ($i = 0; $i < $nums - 1; ++$i) {
            $csv_data .= '"' . $title_arr[$i] . '",';
        }
        if ($nums > 0) {
            $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
        }

        $tuan = $this->cartuan->get_cartuan(array('status' => 1), 'cartuan.*,car_weixin_mobile.mobile');
        if($tuan){
            foreach($tuan as $key =>$val){
                $r = $this->cartuan->get_cartuan_member(array('cartuanyuan.tuan_id' => $val['id'], 'car_weixin_mobile.mobile != ' => $val['mobile']),'car_weixin_mobile.mobile');
                $tuanyuan = '';
                if($r){
                    foreach($r as $v){
                        $tuanyuan .= $v['mobile'].',';
                    }
                    $tuanyuan = substr($tuanyuan,0,-1);
                }else{
                    $tuanyuan = '';
                }
                $tuan[$key]['tuanyuan'] = $tuanyuan;
            }
        }
        $data = $tuan;
        foreach ($data as $k => $row) {
            $row = array_values($row);
            for ($i = 0; $i < $nums - 1; ++$i) {
                $row[$i] = str_replace("\"", "\"\"", $row[$i]);
                switch($i){
                    case 0 : $csv_data .= '"' . $row[4] . ',",';break;
                    case 1 : $csv_data .= '"' . $row[5] . ',",';break;
                    case 2 : $csv_data .= '"' . $row[2] . '",';break;
                }
            }
            $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
            unset($data[$k]);
        }
        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
        $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { // 解决IE浏览器输出中文名乱码的bug
            $file_name = urlencode($file_name);
            $file_name = str_replace('+', '%20', $file_name);
        }
        $file_name = $file_name . '.csv';
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

}
